package ch13;

public class ThreadWork{

	private int j=10;
	
	public synchronized void add() {
		j++;
		System.out.println(Thread.currentThread().getName()+"add: "+j);
	}
	
	public synchronized void subtraction() {
		j--;
		System.out.println(Thread.currentThread().getName()+"subtraction: "+j);
	}

	class Add implements Runnable {
		public void run() {
			for(int i=0;i<10;i++) {
				add();
			}
			System.out.println("加法子进程结束一次");
		}
			
	}
	
	class Subtraction implements Runnable {
		public void run() {
			for(int i=0;i<10;i++) {
				subtraction();
			}
			System.out.println("加法子进程结束一次");
		}
	}
	
	public static void main(String[] args) {
		ThreadWork threadwork = new ThreadWork();
		Add add = threadwork.new Add();
		Subtraction subtraction = threadwork.new Subtraction();
		
		for(int i=0;i<2;i++) {
			Thread thread = new Thread(add);
			Thread thread2 = new Thread(subtraction);
			
			thread.start();
			thread2.start();
		}
		
	}

}
